package com.coder4j.task;

import com.alibaba.fastjson.JSON;
import com.coder4j.biz.entity.AiWanxiangEntity;
import com.coder4j.biz.service.AiWanxiangService;
import com.coder4j.biz.vo.AiWanxiangQuery;
import com.coder4j.starter.tools.enums.StatusEnums;
import com.coder4j.starter.tools.util.FileUtils;
import com.coder4j.starter.tools.util.StringUtils;
import com.coder4j.system.entity.SysConfigEntity;
import com.coder4j.system.service.SysConfigService;
import com.coder4j.system.vo.SysConfigQuery;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;



@Component
@Slf4j
public class WanXiangTask {

    @Resource
    private AiWanxiangService service;

    @Resource
    private SysConfigService configService;

    /**
     * 间隔时间 15分钟
     */
    private static long intervalTime = 15 * 60 * 1000;

    private static String wanxiangCookies = "AliWanXiang_Cookies";

    private static String url = "https://wanxiang.aliyun.com/wanx/api/common/imageGen";

//    @Scheduled(cron = "0 * * * * ?")
    public void executeTask() {
        log.info("----------executeTask--------任务每分钟执行一次 {}" , System.currentTimeMillis());

        AiWanxiangQuery query = new AiWanxiangQuery();
        query.setState(StatusEnums.Doing.name());

        AiWanxiangEntity entity = service.baseQueryOne(query);

        //如果有正在执行的任务
        if(entity != null){
            Date now = new Date();
            //时间间隔小于15分钟，返回
            if(now.getTime() - entity.getUpdateTime().getTime() < intervalTime){
                log.info("----------有正在执行的脚本，本次任务结束---------");
                return;
            }
            //时间间隔大于15分钟，状态修改为：已完成
            entity.setState(StatusEnums.Finish.name());
            service.baseSave(entity);
        }

        query.setState(StatusEnums.Waiting.name());
        entity = service.baseQueryOne(query);
        if(entity != null){
            this.execute(entity);
            log.info("----------开始执行新脚本----------");
        }else{
            log.info("----------没有新脚本，本次任务结束----------");
        }
    }

    private void execute(AiWanxiangEntity entity){
        SysConfigQuery query = new SysConfigQuery();
        query.setName(wanxiangCookies);
        SysConfigEntity config = configService.baseQueryOne(query);

        if(config == null){
            return;
        }

        entity.setCookies(config.getValue());

        this.text2Video(entity);


        entity.setState(StatusEnums.Doing.name());
        service.baseSave(entity);
    }

    public AiWanxiangEntity text2Video(AiWanxiangEntity entity){

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<ResponseVO> response;

        TaskInput input = new TaskInput();
        input.setPrompt(entity.getPrompt());
        input.setResolution("1280*720");
        input.setGenerationMode("plain");
        input.setVideoSoundSwitch("off");

        Task task = new Task();
        task.setTaskType("text_to_video");
        task.setTaskInput(input);

        log.info("request:{}", JSON.toJSONString(task));
        //构建新的请求头对象，并复制原有的值
        HttpEntity<Task> requestEntity = new HttpEntity<>(task, this.getHeaders(entity.getCookies()));
        response = restTemplate.postForEntity( url, requestEntity, ResponseVO.class);
        //发送POST请求并获取响应
        log.info("response:{}",response);
        log.info("response:{}",response.getBody());

        //{"success":true,"errorCode":"0","data":"7625d263c9ba417381ed79a964b2f005","requestId":"0bc3b2d917337323403942947e2e3a","failed":false}
        entity.setBizId(response.getBody().getData());
        entity.setResponse(JSON.toJSONString(response.getBody()));
        return entity;

    }

    @Data
    public static class Task {
        private String taskType;
        private TaskInput taskInput;
    }

    @Data
    public static class TaskInput {
        private String prompt;
        private String resolution;
        private String generationMode;
        private String videoSoundSwitch;
    }


    @Data
    public static class ResponseVO{
        private boolean success;
        private String errorCode;
        private String data;
        private String requestId;
        private boolean failed;
    }

    public HttpHeaders getHeaders(String cookies){
        HttpHeaders headers = new HttpHeaders();
        for (String str : cookies.trim().split(";")) {
            if(StringUtils.isEmpty(str) || !str.contains("=") || str.split("=").length != 2){
                continue;
            }
            String[] array = str.split("=");
            headers.put(array[0],new ArrayList<String>(){{add(array[1]);}});
        }
        headers.put("Cookie",new ArrayList<String>(){{add(cookies);}});
        return headers;
    }

}
